package com.sirius.test.rabbit;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class TopicReceive {

    private static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();    // 连接工厂
        factory.setHost("192.168.231.128");
		factory.setUsername("admin");
		factory.setPassword("admin");
		factory.setPort(5672);
        Connection connection = factory.newConnection();        // 获取连接
        Channel channel = connection.createChannel();

        // 声明一个topic交换类型
        channel.exchangeDeclare(EXCHANGE_NAME, "topic");

        // 当声明队列，不加任何参数，产生的将是一个临时队列，getQueue返回的是队列名称
        String queueA = channel.queueDeclare().getQueue();
        String queueB = channel.queueDeclare().getQueue();
        System.out.println("临时队列：" + queueA);
        System.out.println("临时队列：" + queueB);

        // 第三个参数为“绑定建”
        // * 可以代替一个单词。
        // ＃ 可以替代零个或多个单词。
        channel.queueBind(queueA, EXCHANGE_NAME, "*.orange.*");
        channel.queueBind(queueB, EXCHANGE_NAME, "*.*.rabbit");
        channel.queueBind(queueB, EXCHANGE_NAME, "lazy.#");

        Consumer consumerA = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String recv = new String(body, "UTF-8");
                System.out.println("Direct-Receive-A:" + recv);
            }
        };
        Consumer consumerB = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String recv = new String(body, "UTF-8");
                System.out.println("Direct-Receive-B:" + recv);
            }
        };
        channel.basicConsume(queueA, true, consumerA);
        channel.basicConsume(queueB, true, consumerB);
    }
}
